<?php

namespace App\Models\Admin;

use App\Api\Traits\DateTrait;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Str;
use Laravel\Sanctum\HasApiTokens;
use Laravel\Sanctum\NewAccessToken;
use Spatie\Permission\Traits\HasRoles;

class AdminUser extends Authenticatable
{
    use HasApiTokens, HasRoles, DateTrait;

    protected $hidden = ['password'];
    protected $guarded = [];
    protected string $guard_name = 'sanctum';

    /**
     * Create a new personal access token for the user.
     *
     * @param string $name
     * @param array|string $abilities
     * @return NewAccessToken
     */
    public function updateOrCreateToken(string $name, array|string $abilities = '*'): NewAccessToken
    {
        $token = $this->tokens()->where(['abilities' => '["' . $abilities . '"]', 'name' => $name])->first();
        if ($token) {
            $token->update(['token' => hash('sha256', $plainTextToken = Str::random(40))]);
            return new NewAccessToken($token, $token->getKey() . '|' . $plainTextToken);
        }
        return $this->createToken($name, [$abilities]);
    }

    /**
     * @return BelongsTo
     */
    public function department(): BelongsTo
    {
        return $this->belongsTo(AdminDepartment::class);
    }
}
